package com.hqyj.onlineExamination.config;

import com.hqyj.onlineExamination.interceptor.RequestViewMappingInterceptor;
import com.hqyj.onlineExamination.modules.common.entity.ResourceConfigBean;
import org.apache.catalina.connector.Connector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.web.servlet.WebMvcAutoConfiguration;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.ResourceUtils;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

// 此时项目已经支持Https协议，但不支持Http协议
// 添加配置类WebMvcConfig，为Servlet容器添加Http连接器
@Configuration
@AutoConfigureAfter({WebMvcAutoConfiguration.class})
public class WebMvcConfig implements WebMvcConfigurer {

    //注入静态资源配置bean
    @Autowired
    private ResourceConfigBean resourceConfigBean;

    //注入拦截器bean
    @Autowired
    private RequestViewMappingInterceptor requestViewMappingInterceptor;

    /*
     * 静态资源配置
     * 将本地文件夹绝对路径 映射为 SpringBoot识别的一个相对路径
     * */
    //添加资源控制类addResourceHandlers，添加一个新的静态资源
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //获取系统名称
        String systemName = System.getProperty("os.name");
        //如果是Windows
        if (systemName.toLowerCase().startsWith("win")) {
            //把本地的资源文件夹"file:"+"F:/upload/" 映射为SpringBoot识别的一个相对路径"/upload/**",
            //之后便可以通过"127.0.0.1:81/upload/**"访问或操作"F:/upload/"这个文件夹
            //registry.addResourceHandler("/upload/**").addResourceLocations("file:"+"F:/upload/");
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + resourceConfigBean.getLocalPathForWindow());
        } else {
            registry.addResourceHandler(resourceConfigBean.getResourcePathPattern())
                    .addResourceLocations(ResourceUtils.FILE_URL_PREFIX + resourceConfigBean.getLocalPathForLinux());
        }
    }

    //重写拦截器方法，配置自定义的拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(requestViewMappingInterceptor).addPathPatterns("/**");
    }
}

